package com.yutianran.ezadapter;

import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class CommonViewHolder<D> extends RecyclerView.ViewHolder {
    private SparseArray<View> views;

    public CommonViewHolder(View view) {
        super(view);
        this.views = new SparseArray<>();
    }

    public <T extends View> T getView(int viewId) {
        View view = views.get(viewId);
        if (view == null) {
            view = itemView.findViewById(viewId);
            views.put(viewId, view);
        }
        return (T) view;
    }

    public View getItemView() {
        return itemView;
    }

    /**
     * 适配ListView
     *
     * @param convertView
     * @param parent
     * @param layoutId
     * @return
     */
    public static CommonViewHolder get(View convertView, ViewGroup parent, int layoutId) {
        CommonViewHolder viewHolder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
            viewHolder = new CommonViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (CommonViewHolder) convertView.getTag();
        }
        return viewHolder;
    }
}
